package com.xoa.service.WFE.WFEFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.WFE.WFEFlowProcessMapper;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.flowRunFeedback.FlowRunFeedbackMapper;
import com.xoa.dao.flowplugin.FlowPluginMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.dao.workflow.FlowTiggerMapper;
import com.xoa.dao.workflow.FlowTypeModelMapper;
import com.xoa.model.department.Department;
import com.xoa.model.flowRunFeedback.FlowRunFeedback;
import com.xoa.model.flowplugin.FlowPluginModel;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.WFE.WFE;
import com.xoa.service.WFE.WFERunner.WFEFlowRun;
import com.xoa.service.work.WorkService;
import com.xoa.util.DateFormat;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class WFEFlowProcess extends WFE {

    @Autowired
    protected WFEFlowProcessMapper wfeFlowProcessMapper;

    @Autowired
    protected WFEFlowRunPrcsMapper wfeFlowRunPrcsMapper;

    @Autowired
    protected FlowTiggerMapper flowTiggerMapper;

    @Autowired
    protected FlowPluginMapper flowPluginMapper;

    @Autowired
    protected WorkService workService;

    @Autowired
    protected FlowRunFeedbackMapper flowRunFeedbackMapper;

    @Autowired
    protected FlowRunPrcsMapper flowRunPrcsMapper;

    @Autowired
    protected UsersMapper userMapper;

    @Autowired
    protected FlowTypeModelMapper flowTypeModelMapper;

    @Autowired
    protected WFEFlowRun wfeFlowRun;


    public FlowProcess find(int id) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("id", id);
        FlowProcess flowProcess = wfeFlowProcessMapper.find(maps);
        return flowProcess;
    }

    public List<FlowProcess> findProcseePrcsTo(Map<String, Object> map) {
        return wfeFlowProcessMapper.findProcseePrcsTo(map);
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:  2017年5月10日 上午11:18:20
     * 方法介绍:   （修改后保存）在6/3修改补充json解析，并完善已知bug(张勇)
     * 参数说明:
     *
     * @return
     */
    @Transactional
    public ToJson<FlowProcess> updateByPrimaryKeySelective(FlowProcess record) {
        ToJson<FlowProcess> tojson = new ToJson<FlowProcess>();
        try {
            L.a("itemId：" + record.getITEM_ID());
            L.a("autoPrcsUser：" + record.getAUTO_PRCS_USER());

            // 解析页面json串
            String tlement = record.getSettlementOfCondition();
            if (!StringUtils.checkNull(tlement)) {
                String intoTheCondition = JSONArray.parseObject(tlement).getString("intoTheCondition");
                String transferConditions = JSONArray.parseObject(tlement).getString("transferConditions");
                if (!StringUtils.checkNull(JSONArray.parseObject(intoTheCondition).getString("list"))) {
                    record.setPrcsIn(JSONArray.parseObject(intoTheCondition).getString("list"));
                }
                if (!StringUtils.checkNull(JSONArray.parseObject(transferConditions).getString("list"))) {
                    record.setPrcsOut(JSONArray.parseObject(transferConditions).getString("list"));
                }

                if (!StringUtils.checkNull(JSONArray.parseObject(intoTheCondition).getString("prcsInSet"))) {
                    record.setPrcsInSet(JSONArray.parseObject(intoTheCondition).getString("prcsInSet"));
                }

                if (!StringUtils.checkNull(JSONArray.parseObject(intoTheCondition).getString("conditionDesc")) && !StringUtils.checkNull(JSONArray.parseObject(transferConditions).getString("conditionDesc"))) {
                    String conditions = "";
                    if (StringUtils.checkNull(JSONArray.parseObject(intoTheCondition).getString("conditionDesc"))) {
                        conditions += "";
                    } else {
                        conditions += JSONArray.parseObject(intoTheCondition).getString("conditionDesc");
                    }
                    conditions += "\n";
                    if (StringUtils.checkNull(JSONArray.parseObject(transferConditions).getString("conditionDesc"))) {
                        conditions += "";
                    } else {
                        conditions += JSONArray.parseObject(transferConditions).getString("conditionDesc");
                    }
                    record.setConditionDesc(
                            conditions
                    );
                } else if (!StringUtils.checkNull(JSONArray.parseObject(intoTheCondition).getString("conditionDesc"))) {
                    record.setConditionDesc(JSONArray.parseObject(intoTheCondition).getString("conditionDesc"));
                } else if (!StringUtils.checkNull(JSONArray.parseObject(transferConditions).getString("conditionDesc"))) {
                    record.setConditionDesc("\n" + JSONArray.parseObject(transferConditions).getString("conditionDesc"));
                }
                if (!StringUtils.checkNull(JSONArray.parseObject(transferConditions).getString("prcsOutSet"))) {
                    record.setPrcsOutSet(JSONArray.parseObject(transferConditions).getString("prcsOutSet"));
                }


            }
            // 解析页面json串
            String prcsItem = record.getPrcsItemTwo();
            if (!StringUtils.checkNull(prcsItem)) {
                JSONObject jsonObject = JSONArray.parseObject(prcsItem);
                if (jsonObject != null) {
                    if (!StringUtils.checkNull(jsonObject.getString("prcsItem"))) {
                        record.setPrcsItem(jsonObject.getString("prcsItem"));
                    }
                    if (!StringUtils.checkNull(jsonObject.getString("attachPriv"))) {
                        record.setAttachPriv(jsonObject.getString("attachPriv"));
                    }
                    if (!StringUtils.checkNull(jsonObject.getString("attachEditPriv"))) {
                        record.setAttachEditPriv(jsonObject.getString("attachEditPriv"));
                    }
                    if (!StringUtils.checkNull(jsonObject.getString("attachEditPrivOnline"))) {
                        record.setAttachEditPrivOnline(jsonObject.getString("attachEditPrivOnline"));
                    }
                    if (!StringUtils.checkNull(jsonObject.getString("attachMacroMark"))) {
                        record.setAttachMacroMark(jsonObject.getString("attachMacroMark"));
                    }
                    if (!StringUtils.checkNull(jsonObject.getString("documentEditPriv"))) {
                        record.setDocumentEditPriv(jsonObject.getInteger("documentEditPriv"));
                    }
                    if (!StringUtils.checkNull(jsonObject.getString("documentEditPrivDetail"))) {
                        record.setDocumentEditPrivDetail(jsonObject.getString("documentEditPrivDetail"));
                    }
                }


            }
            if (!StringUtils.checkNull(record.getITEM_ID())) {
                record.setAutoUser(record.getITEM_ID());
            }
            record.setPrcsTo(record.getPrcsTo());
            wfeFlowProcessMapper.updateByPrimaryKeySelective(record);
            tojson.setFlag(0);
            tojson.setMsg("OK");
        } catch (Exception e) {
            e.printStackTrace();
            tojson.setFlag(1);
            tojson.setMsg("error");
        }
        return tojson;
    }


    public List<FlowProcess> findFlowId(int flowId) {
        List<FlowProcess> list = wfeFlowProcessMapper.findFlowId(flowId);
        return list;
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月22日 上午9:44:40
     * 方法介绍:   删除流程
     * 参数说明:   @param id
     *
     * @return void
     */

    @Transactional
    public ToJson<FlowProcess> delete(int id) {
        ToJson<FlowProcess> toJson = new ToJson<FlowProcess>();
        try {
            wfeFlowProcessMapper.deleteByPrimaryKey(id);
            toJson.setFlag(0);
            toJson.setMsg("ok");
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("error");
        }
        return toJson;
    }


    @Transactional(readOnly = true)
    public ToJson<FlowProcessList> flowView(Integer flowId, Integer runId) {
        ToJson<FlowProcessList> toJson = new ToJson(1, "error");
        try {

            //定义
            List<Map<String, String>> lm = new ArrayList<Map<String, String>>();
            //根据flowId获取流程信息
            List<FlowProcess> list = wfeFlowProcessMapper.findF(flowId);
            FlowRun flowRun = null;
            if (runId!=null){
                flowRun = wfeFlowRun.find(runId);
            }
            String autoDeptName = null;
            String autoUserOpName = null;
            String autoUserName = null;
            String userFilterPrcsDeptName = null;
            String userFilterPrcsPrivName = null;
            String userFilterPrcsPrivOtherName = null;
            String userFilterPrcsDeptOtherName = null;
            String preSetUser = null;
            for (FlowProcess flowProcess : list) {
                autoDeptName = null;
                autoUserOpName = null;
                autoUserName = null;
                userFilterPrcsDeptName = null;
                userFilterPrcsPrivName = null;
                userFilterPrcsPrivOtherName = null;
                userFilterPrcsDeptOtherName = null;
                //获取所有经办人
               /* Map<String, Object> mapUser = new HashMap<String, Object>();
                mapUser.put("flowId", flowProcess.getFlowId());
                mapUser.put("prcsId", flowProcess.getPrcsId());
                mapUser.put("prcsPriv", flowProcess.getPrcsPriv() == "" ? null : flowProcess.getPrcsPriv().split(","));
                mapUser.put("prcsDept", flowProcess.getPrcsDept() == "" ? null : flowProcess.getPrcsDept().split(","));
                List<Users> allUser = usersService.getAllUser(mapUser);

                flowProcess.setAllUser(allUser);*/

                if (!StringUtils.checkNull(flowProcess.getAutoUserOp())) {
                    autoUserOpName = usersService.getUserNameById(flowProcess.getAutoUserOp());
                }
                if (!StringUtils.checkNull(flowProcess.getAutoUser())) {
                    autoUserName = usersService.getUserNameById(flowProcess.getAutoUser());
                }
                if (!StringUtils.checkNull(flowProcess.getAutoDept())) {
                    Department d = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept()));
                    if (d != null) {
                        autoDeptName = d.getDeptName();
                    }
                }
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsDept())) {
                    userFilterPrcsDeptName = departmentService.getDeptNameByDeptId(flowProcess.getUserFilterPrcsDept(), ",");
                }
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsDeptOther())) {
                    userFilterPrcsDeptOtherName = departmentService.getDeptNameByDeptId(flowProcess.getUserFilterPrcsDeptOther(), ",");
                }
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsPriv())) {
                    userFilterPrcsPrivName = usersPrivService.getPrivNameByPrivId(flowProcess.getUserFilterPrcsPriv(), ",");
                }
                if (!StringUtils.checkNull(flowProcess.getUserFilterPrcsPrivOther())) {
                    userFilterPrcsPrivOtherName = usersPrivService.getPrivNameByPrivId(flowProcess.getUserFilterPrcsPrivOther(), ",");
                }
                if (!StringUtils.checkNull(flowProcess.getAutoUser())) {
                    if ("7".equals(flowProcess.getAutoType())) {
                        String temp = flowProcess.getAutoUser();
                        String[] t = temp.split(",");
                        String dataTemp = "";
                        for (int i = 0, length = t.length; i < length; i++) {
                            dataTemp = dataTemp + "DATA_" + t[i] + ",";
                        }
                        flowProcess.setAutoUser(dataTemp);
                    }
                }
                flowProcess.setAutoUserName(autoUserName);
                flowProcess.setAutoUserOpName(autoUserOpName);
                flowProcess.setAutoDeptName(autoDeptName);
                flowProcess.setUserFilterPrcsDeptName(userFilterPrcsDeptName);
                flowProcess.setUserFilterPrcsPrivName(userFilterPrcsPrivName);
                flowProcess.setUserFilterPrcsPrivOtherName(userFilterPrcsPrivOtherName);
                flowProcess.setUserFilterPrcsDeptOtherName(userFilterPrcsDeptOtherName);
                //获取每个步骤的流程预设信息
                if ("1".equals(flowProcess.getPresetYN())){
                    if (flowRun!=null&&!StringUtils.checkNull(flowRun.getPresetUser())){
                        preSetUser = this.getPrseSetUser(flowRun.getPresetUser(),flowProcess.getPrcsId().toString());
                        if (!StringUtils.checkNull(preSetUser)){
                            flowProcess.setPresetUserIds(preSetUser);
                            flowProcess.setPresetUser(usersService.getUserNameById(preSetUser));
                        }
                    }
                }
            }
            List<FlowRunPrcs> runPrcsList = new ArrayList<FlowRunPrcs>();
            if (runId != null) {
                runPrcsList = wfeFlowRunPrcsMapper.selectAllByRunId(runId);
            }
            if (list != null && list.size() > 0) {
                int len = list.size();
                //f.setFlowName(list.get(0).getFlowName());
                //list.get(len - 1).setSetType("end round");
                list.get(0).setSetType("start");
                for (int i = 0; i < len; i++) {
                    Integer prId = list.get(i).getPrcsId();
                    String prcsTo = list.get(i).getPrcsTo();
                    if (!StringUtils.checkNull(prcsTo)) {
                        Map<String, String>  map = new HashMap<String, String>();
                       /* map = new HashMap<String, String>();
                        map.put("from", Integer.toString(prId));
                        if (i < len - 1) {
                            if (list.get(i + 1).getPrcsId() == prId + 1) {
                                map.put("to", Integer.toString(list.get(i + 1).getPrcsId()));
                            }
                        } else {
                            map.put("to", "end");
                        }
                        lm.add(map);
                    } else {*/
                        String[] p = prcsTo.split(",");
                        for (String a : p) {
                            if (!"0".equals(a)) {
                                map.put("from", Integer.toString(prId));
                                map.put("to", a);
                                lm.add(map);
                            } else {
                                map.put("from", Integer.toString(prId));
                                map.put("to", "end");
                                list.get(i).setSetType("end round");
                                lm.add(map);
                            }
                            map = new HashMap<String, String>();
                        }
                    }
                }

            }

            FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
            //汉字转换方法
            List<FlowProcess> listp = this.returnChinese(list);
            for (FlowProcess list1:listp){
                if (!StringUtils.checkNull(list1.getAutoArchiveSet())){
                    String autoArchiveSet = list1.getAutoArchiveSet();
                    String file = JSONArray.parseObject(autoArchiveSet).getString("file");
                    String rmsRollRoom = JSONArray.parseObject(autoArchiveSet).getString("rmsRollRoom");
                    String rmsRoll = JSONArray.parseObject(autoArchiveSet).getString("rmsRoll");
                    String fileRule = JSONArray.parseObject(autoArchiveSet).getString("fileRule");//是否强制归档（0不强制归档，1强制归档
                    String mappingRule = JSONArray.parseObject(autoArchiveSet).getString("mappingRule");//归档字段映射规则
                    String fileContent = JSONArray.parseObject(autoArchiveSet).getString("fileContent");

                    list1.setFile(file);
                    list1.setRmsRollRoom(rmsRollRoom);
                    list1.setRmsRoll(rmsRoll);
                    list1.setFileRule(fileRule);
                    list1.setMappingRule(mappingRule);
                    list1.setFileContent(fileContent);
                }
            }
            //定义用于返回的流程信息
            FlowProcessList flowProcessList = new FlowProcessList();
            flowProcessList.setConnections(lm);
            flowProcessList.setDesigndata(listp);
            flowProcessList.setMax(listp.size());
            flowProcessList.setFlowRunPrcsList(runPrcsList);
            flowProcessList.setFlowName(flowTypeModel.getFlowName());
            toJson.setObject(flowProcessList);

            toJson.setFlag(0);
            toJson.setMsg("ok");
        } catch (Exception e) {
            L.e("FlowProcessServiceImpl flowView:" + e);
        }
        return toJson;
    }

    @Transactional
    public ToJson<FlowProcess> insertSelective(FlowProcess record) {
        ToJson<FlowProcess> toJson = new ToJson<FlowProcess>();
        try {
            wfeFlowProcessMapper.insert(record);
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObject(record);
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("error");
        }
        return toJson;
    }

    public FlowProcess findbyprcsId(int flowId, int prcsId) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("flowId", flowId);
        maps.put("prcsId", prcsId);
        FlowProcess flowProcess = wfeFlowProcessMapper.findbyprcsId(maps);
        return flowProcess;
    }
    /**
     * 根据flowId和PrcsId查询步骤主键和下一步指向
     * @return
     */
    public FlowProcess getFpByPrcsId(int flowId, int prcsId) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("flowId", flowId);
        maps.put("prcsId", prcsId);
        FlowProcess flowProcess = wfeFlowProcessMapper.getFpByPrcsId(maps);
        return flowProcess;
    }

    //返回所有经办人数据
    public List<Users> reAllUser(FlowProcess flowProcess) {
        //经办人串
        String prcsUser = flowProcess.getPrcsUser();
        //经办人部门id串
        String prcsDept = flowProcess.getPrcsDept();
        //经办角色id串
        String prcsPriv = flowProcess.getPrcsPriv();
        //用来存储经办人信息
        List<Users> prcsUserlist = new ArrayList<Users>();
        //用来存储经办部门信息
        List<Users> prcsDeptlist = new ArrayList<Users>();
        //用来存储经办角色信息
        List<Users> prcsPrivlist = new ArrayList<Users>();
        //用来存储所有经办信息
        List<Users> allUser = new ArrayList<Users>();

        if (!StringUtils.checkNull(prcsUser)) {
            //查询所有符合条件经办人信息集合
            prcsUserlist = usersService.getUserByuserId(flowProcess.getPrcsUser());
        }
        if (!StringUtils.checkNull(prcsDept)) {
            prcsDeptlist = usersService.getUserByDeptIds(prcsDept, 5);
        }
        if (!StringUtils.checkNull(prcsPriv)) {
            prcsPrivlist = usersService.getUserByDeptIds(prcsPriv, 6);
        }
        allUser.addAll(prcsUserlist);
        allUser.addAll(prcsDeptlist);
        allUser.addAll(prcsPrivlist);
        //去重
        Map<Integer, Users> m = new HashMap<Integer, Users>();
        for (Users users1 : allUser) {
            m.put(users1.getUid(), users1);
        }
        allUser = new ArrayList<Users>(m.values());

        return allUser;
    }


    /**
     * 创建作者:   张勇
     * 创建日期:   2017/6/3 11:24
     * 方法介绍:   修改流程节点坐标
     * 参数说明:
     *
     * @return
     */
    @Transactional
    public ToJson<FlowProcess> updateTopAndLeft(FlowProcess flowProcess) {
        ToJson<FlowProcess> toJson = new ToJson<FlowProcess>();
        FlowProcess prcsTo = wfeFlowProcessMapper.findLine(flowProcess.getId());
        try {
            if (prcsTo.getPrcsTo().equals("0") || prcsTo.getPrcsTo().equals("0,")) {
                wfeFlowProcessMapper.updateTopAndLeft(flowProcess);
            } else if (StringUtils.checkNull(prcsTo.getPrcsTo())) {
                if (flowProcess.getPrcsTo().equals("")) {
                    flowProcess.setPrcsTo((prcsTo.getPrcsId() + 1) + ",");
                    wfeFlowProcessMapper.updateTopAndLeft(flowProcess);
                } else {
                    wfeFlowProcessMapper.updateTopAndLeft(flowProcess);
                }
            }
            if (prcsTo.getPrcsTo() != "") {
                String prcsToI = prcsTo.getPrcsTo();
                StringBuffer prcsTo1 = new StringBuffer(prcsToI);
                String[] prcsToId = flowProcess.getPrcsTo().split(",");
                int len = prcsToId.length;
                for (int i = 0; i < len; i++) {
                    if (!prcsToI.contains(prcsToId[i])) {
                        prcsTo1.append(prcsToId[i] + ",");
                    }
                }
                flowProcess.setPrcsTo(prcsTo1.toString());
                wfeFlowProcessMapper.updateTopAndLeft(flowProcess);
            }
            toJson.setFlag(0);
            toJson.setMsg("ok");
        } catch (Exception e) {
            toJson.setTotleNum(1);
            toJson.setMsg("error");
        }
        return toJson;
    }

    /**
     * 部门id转换为部门名字
     *
     * @param name
     * @return
     */
    public String deptName(String name) {
        String deptName = null;
//        getDeptNameById
        return deptName;
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/6/8 17:30
     * 方法介绍:   连接线删除
     * 参数说明:
     *
     * @return
     */

    @Transactional
    public ToJson<FlowProcess> findPrcessLine(FlowProcess flowProcesse, String toPrcsLine) {
        ToJson<FlowProcess> toJson = new ToJson<FlowProcess>();
        FlowProcess flowProcess = wfeFlowProcessMapper.findPrcessLine(flowProcesse.getFlowId(), flowProcesse.getPrcsId());
        FlowProcess fpr = new FlowProcess();
        try {
            if (StringUtils.checkNull(flowProcess.getPrcsTo())) {
                fpr.setId(flowProcess.getId());
                fpr.setPrcsTo("0");
                wfeFlowProcessMapper.updateTopAndLeft(fpr);
            } else {
                String[] prcsTo = flowProcess.getPrcsTo().split(",");
                int leng = prcsTo.length;
                if (leng == 1) {
                    fpr.setId(flowProcess.getId());
                    fpr.setPrcsTo("");
                    wfeFlowProcessMapper.updateTopAndLeft(fpr);
                } else {
                    String names = "";
                    for (int i = 0; i < leng; i++) {
                        String prcsToI = prcsTo[i];
                        if (!prcsToI.equals(toPrcsLine)) {
                            names += (prcsToI + ",");
                        }
                    }
                    fpr.setId(flowProcess.getId());
                    fpr.setPrcsTo(names);
                    wfeFlowProcessMapper.updateTopAndLeft(fpr);
                }
            }
            toJson.setFlag(0);
            toJson.setMsg("ok");
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("error");
            L.e("Process findPrcessLine:" + e);
        }
        return toJson;
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/7/13 10:58
     * 方法介绍:   触发器执行方式和触发节点哈希表
     * 参数说明:
     *
     * @return
     */
    public Map<Object, String> returnTiggerValue() {
        Map<Object, String> maps = new HashMap<Object, String>();
        // 执行方式
        maps.put("BEFORE_FRONTEND", "前台,执行操作前");
        maps.put("AFTER_FRONTEND", "前台,执行操作后");
        maps.put("BEFORE_BACKEND", "后台,执行操作前");
        maps.put("AFTER_BACKEND", "后台,执行操作后");

        // 触发节点
        maps.put("CREATE", "新建操作");
        maps.put("RECEIVE", "接收操作");
        maps.put("SAVE", "保存操作");
        maps.put("TURN", "转交操作");
        maps.put("INTRUST", "委托操作");
        maps.put("BACK", "退回操作");

        // 查询插件名字放到哈希表
        List<FlowPluginModel> list = flowPluginMapper.showFlowPlugin();
        if (list.size() > 0) {
            for (FlowPluginModel flp : list) {
                maps.put(flp.getFlowPluginId(), flp.getFlowPluginName());
            }
        }
        return maps;
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/7/14 13:21
     * 方法介绍:    我经办的步骤
     * 参数说明:  flowId 流程ID  prcsId 流程步骤
     *
     * @return
     */
    @SuppressWarnings("all")
    public ToJson myFlowView(Integer flowId, Integer runId, String userId) {
        ToJson toJson = new ToJson(1, "error");
        try {
            Map<String, String> map = null;
            //定义
            List<Map<String, String>> lm = new ArrayList<Map<String, String>>();
            //根据flowId获取流程信息
            List<FlowProcess> list = wfeFlowProcessMapper.findF(flowId);
            for (FlowProcess flowProcess : list) {
                String autoUserOpName = usersService.findUsersByuid(flowProcess.getAutoUserOp());
                String autoUserName = usersService.findUsersByuid(flowProcess.getAutoUser());
                String autoDeptName = departmentService.getDeptById(Integer.parseInt(flowProcess.getAutoDept())).getDeptName();
                flowProcess.setAutoUserName(autoUserName);
                flowProcess.setAutoUserOpName(autoUserOpName);
                flowProcess.setAutoDeptName(autoDeptName);
            }
            List<FlowRunPrcs> runPrcsList = wfeFlowRunPrcsMapper.selectMyAll(userId, runId);
            int listLength = list.size();
            int runPrcsListLenth = runPrcsList.size();
            //处理下标
            if (listLength > runPrcsListLenth) {
                for (int i = listLength - 1; i >= runPrcsListLenth; i--) {
                    list.remove(i);
                }
            }
            Date newDate = new Date();
            for (int i = 0; i < runPrcsListLenth; i++) {
                Integer prId = list.get(i).getPrcsId();
                String prceTo = list.get(i).getPrcsTo();
                if (StringUtils.checkNull(prceTo)) {
                    map = new HashMap<String, String>();
                    map.put("from", Integer.toString(prId));
                    if (i < runPrcsListLenth - 1) {
                        if (list.get(i + 1).getPrcsId() == prId + 1) {
                            map.put("to", Integer.toString(list.get(i + 1).getPrcsId()));
                        }
                    } else {
                        map.put("to", "end");
                    }
                    lm.add(map);
                } else {
                    String[] p = prceTo.split(",");
                    for (String a : p) {
                        if (!"0".equals(a)) {
                            map = new HashMap<String, String>();
                            map.put("from", Integer.toString(prId));
                            map.put("to", a.toString());
                            lm.add(map);
                        } else {
                            map = new HashMap<String, String>();
                            map.put("from", Integer.toString(prId));
                            map.put("to", "end");
                            list.get(i).setSetType("end round");
                            lm.add(map);
                        }
                    }
                }
                // 处理时间和姓名转换
                runPrcsList.get(i).setUserName(usersService.getUserNameById(runPrcsList.get(i).getUserId()));

                if (DateFormat.getTime(runPrcsList.get(i).getPrcsTime()) != -621701856) {
                    // 工作接收时间
                    runPrcsList.get(i).setReceive(DateFormat.getStrTime(DateFormat.getTime(runPrcsList.get(i).getPrcsTime())));
                    // 办理停留时间
                    runPrcsList.get(i).setHandleTime(DateFormat.returnTime((DateFormat.getTime(DateFormat.getStrDate(newDate))) - DateFormat.getTime(runPrcsList.get(i).getPrcsTime())));
                }
                //计算时间转换
                if (DateFormat.getTime(runPrcsList.get(i).getPrcsTime()) != -621701856 && runPrcsList.get(i).getPrcsId() > 1 ||
                        DateFormat.getTime(runPrcsList.get(i).getPrcsTime()) == -621701856 && runPrcsList.get(i).getPrcsId() > 1) {
                    Integer runIds = runPrcsList.get(i).getRunId();
                    String prcsUser = runPrcsList.get(i).getUserId();
                    Integer prcsId = runPrcsList.get(i).getPrcsId() - 1;
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("userId", prcsUser);
                    params.put("prcsId", prcsId);
                    params.put("runId", runId);
                    String upTime = wfeFlowRunPrcsMapper.findTimeBy(params);
                    if (!StringUtils.checkNull(upTime)) {
                        // 到达时间
                        runPrcsList.get(i).setReceiptTime(DateFormat.getStrTime(DateFormat.getTime(upTime)));
                        // 到达停留时间
                        runPrcsList.get(i).setArriveTime(DateFormat.returnTime((DateFormat.getTime(DateFormat.getStrDate(newDate))) - DateFormat.getTime(runPrcsList.get(i).getReceiptTime())));
                    }
                } else {
                    runPrcsList.get(i).setReceiptTime(DateFormat.getStrTime(DateFormat.getTime(runPrcsList.get(i).getPrcsTime())));
                    runPrcsList.get(i).setArriveTime(DateFormat.returnTime((DateFormat.getTime(DateFormat.getStrDate(newDate))) - DateFormat.getTime(runPrcsList.get(i).getPrcsTime())));
                    runPrcsList.get(i).setReceive("");
                    runPrcsList.get(i).setHandleTime("");
                }
            }

            // 转换为汉字
            List<FlowProcess> listp = this.returnChinese(list);
            //定义用于返回的流程信息
            FlowProcessList flowProcessList = new FlowProcessList();
            flowProcessList.setConnections(lm);
            flowProcessList.setDesigndata(listp);
            flowProcessList.setMax(listp.size());
            flowProcessList.setFlowRunPrcsList(runPrcsList);
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObject(flowProcessList);
        } catch (Exception e) {
            L.e("FlowProcessServiceImpl myFlowView:" + e);
        }
        return toJson;
    }


    public ToJson getFlowAttachment(String runId, String conpany) {
        return workService.findworkUpload(runId, conpany);
    }

    public ToJson selectFlowFeedBackByRunId(String runId) {
        List<FlowRunFeedback> datas = flowRunFeedbackMapper.selectFlowFeedBackByRunId(runId);
        ToJson json = new ToJson();
        json.setObj(datas);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }

    public BaseWrappers getFlowRunPrecsAll(String runId) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        if (StringUtils.checkNull(runId)) {
            wrappers.setFlag(false);
            wrappers.setMsg("失败");
            return wrappers;
        }
        List<Map<String, String>> lm = new ArrayList<Map<String, String>>();
        // String flowId = wfeFlowProcessMapper.queryFlowId(runId);
        //  List<FlowProcess> list = wfeFlowProcessMapper.findF(Integer.valueOf(flowId));

        List<FlowRunPrcs> datas = wfeFlowRunPrcsMapper.getFlowRunReacsAllByRunId(runId);
        int runPrcsListLenth = datas.size();
        Date newDate = new Date();
        Map<String, String> map1 = null;
      /*  for (int i = 0; i < runPrcsListLenth; i++) {
            Integer prId = list.get(i).getPrcsId();
            String prceTo = list.get(i).getPrcsTo();
            if (StringUtils.checkNull(prceTo)) {
                map1 = new HashMap<String, String>();
                map1.put("from", Integer.toString(prId));
                if (i < runPrcsListLenth - 1) {
                    if (list.get(i + 1).getPrcsId() == prId + 1) {
                        map1.put("to", Integer.toString(list.get(i + 1).getPrcsId()));
                    }
                } else {
                    map1.put("to", "end");
                }
                lm.add(map1);
            } else {
                String[] p = prceTo.split(",");
                for (String a : p) {
                    if (!"0".equals(a)) {
                        map1 = new HashMap<String, String>();
                        map1.put("from", Integer.toString(prId));
                        map1.put("to", a.toString());
                        lm.add(map1);
                    } else {
                        map1 = new HashMap<String, String>();
                        map1.put("from", Integer.toString(prId));
                        map1.put("to", "end");
                        list.get(i).setSetType("end round");
                        lm.add(map1);
                    }
                }
            }
        }*/

        for (FlowRunPrcs runPrcs : datas) {
            if (Integer.parseInt(runPrcs.getPrcsFlag()) <= 2 ||"6".equals(runPrcs.getPrcsFlag()) ) {
                // 到达时间
                if(!StringUtils.checkNull(runPrcs.getCreateTime()))
                    runPrcs.setArriveTime(DateFormat.returnTime((DateFormat.getTime(DateFormat.getStrDate(newDate))) - DateFormat.getTime(runPrcs.getCreateTime())));
                // 办理时长
                if (DateFormat.getTime(runPrcs.getPrcsTime()) == -621701856) {
                    if("1".equals(runPrcs.getPrcsFlag())){
                        runPrcs.setHandleTime("未接收");
                        runPrcs.setPrcsTime("");
                    }else if ("6".equals(runPrcs.getPrcsFlag())){
                        runPrcs.setHandleTime("已挂起");
                        runPrcs.setPrcsTime("");
                    }
                } else {
                    runPrcs.setHandleTime(DateFormat.returnTime((DateFormat.getTime(DateFormat.getStrDate(newDate))) - DateFormat.getTime(runPrcs.getPrcsTime())));

                }
            } else {
                if(!StringUtils.checkNull(runPrcs.getDeliverTime())){
                    // 到达时间
                    if(!StringUtils.checkNull(runPrcs.getCreateTime()))
                        runPrcs.setArriveTime(DateFormat.returnTime((DateFormat.getTime(runPrcs.getDeliverTime())) - DateFormat.getTime(runPrcs.getCreateTime())));
                    //办理时间
                    if(!StringUtils.checkNull(runPrcs.getPrcsTime()))
                        runPrcs.setHandleTime(DateFormat.returnTime((DateFormat.getTime(runPrcs.getDeliverTime())) - DateFormat.getTime(runPrcs.getPrcsTime())));
                }
            }
            if(!StringUtils.checkNull(runPrcs.getCreateTime()))
                runPrcs.setCreateTime(runPrcs.getCreateTime().substring(0, runPrcs.getCreateTime().length() - 2));
            if (!StringUtils.checkNull(runPrcs.getPrcsTime())) {
                runPrcs.setPrcsTime(runPrcs.getPrcsTime().contains("1950") ? "" : runPrcs.getPrcsTime().substring(0, runPrcs.getPrcsTime().length() - 2));
                if (StringUtils.checkNull(runPrcs.getPrcsTime())) runPrcs.setHandleTime(runPrcs.getArriveTime());
            }
            if (!StringUtils.checkNull(runPrcs.getDeliverTime())) {
                runPrcs.setDeliverTime(runPrcs.getDeliverTime().substring(0, runPrcs.getDeliverTime().length() - 2));
            }
        }

        Map<Integer, List<FlowRunPrcs>> map = new HashMap<Integer, List<FlowRunPrcs>>();
        List<FlowRunPrcs> flowRunPrcsList = null;
        for (int i = 0; i < datas.size(); i++) {
            FlowRunPrcs flowRunPrcs = datas.get(i);
            if (map.keySet().contains(flowRunPrcs.getPrcsId())) {
                flowRunPrcsList = map.get(flowRunPrcs.getPrcsId());
                flowRunPrcsList.add(flowRunPrcs);
            } else {
                flowRunPrcsList = new ArrayList<FlowRunPrcs>();
                flowRunPrcsList.add(flowRunPrcs);
                map.put(flowRunPrcs.getPrcsId(), flowRunPrcsList);
            }

        }


      /*  for (FlowRunPrcs flowRunPrcs : datas) {
           if (map.keySet().contains(flowRunPrcs.getPrcsId())){
                flowRunPrcsList = map.get(flowRunPrcs.getPrcsId());
                flowRunPrcsList.add(flowRunPrcs);
            }else {
            flowRunPrcsList = new ArrayList<FlowRunPrcs>();
            flowRunPrcsList.add(flowRunPrcs);
            map.put(flowRunPrcs.getPrcsId(), flowRunPrcsList);
            }
        }*/
        //1是结束，0是未结束
        List<FlowRunPrcs> list1 = map.get(map.size());
        wrappers.setStatus(true);
        for (FlowRunPrcs flowRunPrcs : datas) {
            if (Integer.parseInt(flowRunPrcs.getPrcsFlag()) < 3) {
                wrappers.setStatus(false);
            }
        }
        wrappers.setFlag(true);
        wrappers.setMsg("0k");
        wrappers.setDatas(datas);
        //wrappers.setObject(map);
        return wrappers;
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/7/14 13:32
     * 方法介绍:   流程设计器返回汉字方法
     * 参数说明:   传递FlowProcess list参数
     *
     * @return
     */
    public List<FlowProcess> returnChinese(List<FlowProcess> list) {
        List<FlowProcess> listp = new ArrayList<FlowProcess>();
        //添加汉字转换方法
        for (FlowProcess flowProcess : list) {
            try {
                if (!StringUtils.checkNull(flowProcess.getPrcsDept())) {
                    //lr+
                    if (flowProcess.getPrcsDept().equals("ALL_DEPT")) {
                        flowProcess.setPrcsDeptName("全部部门");
                    } else {//lr+ else{
                        flowProcess.setPrcsDeptName(departmentService.getDeptNameByDeptId(flowProcess.getPrcsDept(), ","));
                        flowProcess.setPrcsDeptNo(departmentService.getDeptNoByDeptId(flowProcess.getPrcsDept(), ","));
                    }//lr+
                }
                if (!StringUtils.checkNull(flowProcess.getPrcsPriv())) {
                    flowProcess.setPrcsPrivName(usersPrivService.getPrivNameByPrivId(flowProcess.getPrcsPriv(), ","));
                }
                if (!StringUtils.checkNull(flowProcess.getPrcsUser())) {
                    flowProcess.setPrcsUserName(usersService.getUserNameById(flowProcess.getPrcsUser()));
                    flowProcess.setPrcsUserPrivName(usersService.getUserPrivById(flowProcess.getPrcsUser()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<FlowTiggerModel> flowTiggerModel = flowTiggerMapper.selectFlowTigger(flowProcess.getFlowId(), flowProcess.getPrcsId());
            if (flowTiggerModel != null && flowTiggerModel.size() > 0) {
                List<FlowTiggerModel> fltm = new ArrayList<FlowTiggerModel>();
                for (FlowTiggerModel ftm : flowTiggerModel) {
                    ftm.setPluginTypeName(returnTiggerValue().get(ftm.getPluginType()));
                    ftm.setPluginWayName(returnTiggerValue().get(ftm.getPluginWay()));
                    ftm.setPluginName(returnTiggerValue().get(ftm.getPlugin()));
                    fltm.add(ftm);
                }
                flowProcess.setFlowTiggerModel(fltm);
            } else {
                flowProcess.setFlowTiggerModel(new ArrayList<FlowTiggerModel>());
            }
            String autoUserOpReturnName = "";
            String autoUserReturnName ="";
            if(!StringUtils.checkNull(flowProcess.getAutoUserOpReturn())){//主办
                String userId = flowProcess.getAutoUserOpReturn();
                String[] userIdStr = userId.split(",");
                for(String s : userIdStr){
                  Users users =  userMapper.findUsersByuserId(s);
                    autoUserOpReturnName += users.getUserName()+",";
                }
                flowProcess.setAutoUserOpName(autoUserOpReturnName);
            }
            if(!StringUtils.checkNull(flowProcess.getAutoUserReturn())){//经办
                String userId = flowProcess.getAutoUserReturn();
                String[] userIdStr = userId.split(",");
                for(String s : userIdStr){
                    Users users =  userMapper.findUsersByuserId(s);
                    autoUserReturnName += users.getUserName()+",";
                }
                flowProcess.setAutoUserName(autoUserReturnName);
            }
            listp.add(flowProcess);
        }
        return listp;
    }

    public List<FlowProcess> findRunIdFlowId(int flowId, int runId) {
        Map map = new HashMap();
        map.put("flowId", flowId);
        map.put("runId", runId);
        return wfeFlowProcessMapper.findRunIdFlowId(map);
    }

    public BaseWrappers getFlowRunPrecsOpFlag(String runId) {
        BaseWrappers wrappers = new BaseWrappers();
        Map map = new HashMap();
        map.put("runId", runId);
        try {
            //查出当前流程所有会签意见
            List<FlowRunFeedback> flowRunFeedbackList = flowRunFeedbackMapper.selectFeedBackByRunId(map);
            for (FlowRunFeedback flowRunFeedback : flowRunFeedbackList) {
                Map<String, Object> frfmap = new HashMap<String, Object>();
                frfmap.put("userId", flowRunFeedback.getUserId());
                frfmap.put("prcsId", flowRunFeedback.getPrcsId());
                frfmap.put("flowPrcs", flowRunFeedback.getFlowPrcs());
                frfmap.put("runId", runId);
                //将查找后的opFlag付给每一条会签意见
                List<FlowRunPrcs> flowRunPrcsList = flowRunPrcsMapper.getFlowRunPrecsOpFlag(frfmap);
                flowRunFeedback.setOpFlag(flowRunPrcsList.get(0).getOpFlag());
            }
            wrappers.setFlag(true);
            wrappers.setStatus(true);
            wrappers.setObject(flowRunFeedbackList);
        } catch (Exception e) {
            wrappers.setFlag(false);
            wrappers.setMsg("失败");
            e.printStackTrace();
        }
        return wrappers;
    }
     public String findFlowIdPrcsId(Map map){
        return wfeFlowProcessMapper.findFlowIdPrcsId(map);
     }

    public String getPrseSetUser(String preSetUser,String flowPrcs){
        String[] presetUsers = preSetUser.split("\\|");
        String userIds=null;
        for (int i = 0; i <presetUsers.length ; i++) {
            if (flowPrcs.equals(presetUsers[i].split(":")[0])){
                userIds = presetUsers[i].split(":")[1];
                break;
            }

        }
        return userIds;
    }
}
